import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [], // 购物车商品列表
    total: 0, // 购物车总价
  }),
  
  getters: {
    // 获取购物车商品总数
    itemCount: (state) => state.items.reduce((total, item) => total + item.quantity, 0),
    
    // 获取购物车总价
    cartTotal: (state) => state.items.reduce((total, item) => total + (item.price * item.quantity), 0),
  },
  
  actions: {
    // 添加商品到购物车
    addItem(item) {
      const existingItem = this.items.find(i => i.id === item.id)
      if (existingItem) {
        existingItem.quantity += 1
      } else {
        this.items.push({ ...item, quantity: 1 })
      }
    },
    
    // 从购物车移除商品
    removeItem(itemId) {
      this.items = this.items.filter(item => item.id !== itemId)
    },
    
    // 更新商品数量
    updateQuantity(itemId, quantity) {
      const item = this.items.find(i => i.id === itemId)
      if (item) {
        item.quantity = quantity
      }
    },
    
    // 清空购物车
    clearCart() {
      this.items = []
    },
    
    // 检查商品是否在购物车中
    isInCart(itemId) {
      return this.items.some(item => item.id === itemId)
    },
  },
  
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'cart',
        storage: localStorage,
      },
    ],
  },
}) 